package com.fyl.oauth2.domain;

import com.fyl.oauth2.dao.ClientMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class MyBatisRegisteredClientRepository implements RegisteredClientRepository {

    private final ClientMapper clientMapper;

    private final Map<String,RegisteredClient> registeredClients;


    @Autowired
    public MyBatisRegisteredClientRepository(ClientMapper clientMapper) {
        this.clientMapper = clientMapper;
        this.registeredClients = new ConcurrentHashMap<>();
    }

    @PostConstruct
    public void init() {
        List<ClientEntity> clientEntities = clientMapper.findAll();
        clientEntities.forEach(clientEntity -> {
            RegisteredClient registeredClient = ClientEntity.toRegisteredClient(clientEntity);
            registeredClients.put(registeredClient.getId(), registeredClient);
        });
    }


    @Override
    public void save(RegisteredClient registeredClient) {
        ClientEntity clientEntity = ClientEntity.fromRegisteredClient(registeredClient);
        clientMapper.save(clientEntity);
        registeredClients.put(registeredClient.getId(), registeredClient);
    }

    @Override
    public RegisteredClient findById(String id) {
        return registeredClients.get(id);
    }

    @Override
    public RegisteredClient findByClientId(String clientId) {
        return registeredClients.values().stream()
                .filter(registeredClient -> registeredClient.getClientId().equals(clientId))
                .findFirst()
                .orElse(null);
    }
}
